using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using AdRotatorXNA.Helpers;
using Microsoft.Xna.Framework.Input;
using Microsoft.Advertising.WinRT.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using AdRotator.Model;

namespace AdRotatorXNA
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    internal class AdPubcenterComponent : AdComponent
    {
        private static AdPubcenterComponent instance;

        private static Grid _parentGrid;

        public static bool Initialised = false;

        private static AdControl _currentAdControl;

        private AdPubcenterComponent(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
        }


        public static AdPubcenterComponent Current
        {
            get
            {
                if (AdRotatorXNAComponent.game == null)
                    return null;

                if (instance == null)
                    instance = new AdPubcenterComponent(AdRotatorXNAComponent.game);

                return instance;
            }
        }

        public static void Initialize(Game _game, string applicationID)
        {
            if (Initialised)
                return;

            Initialised = true;

            _parentGrid = new Grid();

            var parentCtrl = Window.Current.Content as SwapChainBackgroundPanel;

            parentCtrl.Children.Add(_parentGrid);
        }

        public override void UpdateAd(AdInformation adInfo)
        {
            AdInfo = adInfo;

            if (_currentAdControl != null)
            {
                // If we're "updating" to the same ad, there's no work to be done.
                if (_currentAdControl.ApplicationId == adInfo.AppID &&
                    _currentAdControl.AdUnitId == adInfo.SecondaryID)
                    return;

                RemoveCurrentControl();
            }

            State = AdState.Initialized;

            _currentAdControl = new AdControl()
            {
                ApplicationId = adInfo.AppID,
                AdUnitId = adInfo.SecondaryID,
                Width = adInfo.Width,
                Height = adInfo.Height,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                IsEnabled = false,
                IsTabStop = false,
                IsHitTestVisible = false,
                IsTapEnabled = false,
                IsRightTapEnabled = false
            };

            _currentAdControl.ErrorOccurred += OnAdError;
            _currentAdControl.AdRefreshed += AdRefreshed;

            _parentGrid.Children.Add(_currentAdControl);
        }

        protected override void OnEnabledChanged(object sender, EventArgs args)
        {
            if (!Enabled)
                RemoveCurrentControl();

            base.OnEnabledChanged(sender, args);
        }

        protected override void UnloadContent()
        {
            RemoveCurrentControl();
            base.UnloadContent();
        }

        public void OnAdError(object sender, AdErrorEventArgs args)
        {
            State = AdState.AdFailed;
        }

        private void RemoveCurrentControl()
        {
            if (_currentAdControl == null)
                return;

            _currentAdControl.ErrorOccurred -= OnAdError;
            _currentAdControl.AdRefreshed -= AdRefreshed;
            _parentGrid.Children.Remove(_currentAdControl);

            State = AdState.NotInitialized;

            _currentAdControl = null;
        }

        public void AdRefreshed(object sender, object args)
        {
            State = AdState.AdLoaded;
        }

        public override void UpdatePosition(Vector2 newPos)
        {
            if (_currentAdControl == null)
                return;

            _currentAdControl.Margin = new Thickness()
            {
                Left = newPos.X,
                Top = newPos.Y
            };
        }
    }
}
